package com.example.cardiacmonitor.ecg

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.example.cardiacmonitor.ui.theme.CardiacmonitorTheme
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.exp
import kotlin.math.sin
import kotlin.random.Random
import kotlinx.coroutines.delay

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RealTimePlotScreen(navController: NavHostController) {
    // ECG数据
    var ecgData by remember { mutableStateOf(generateRealisticEcgData(500)) }
    // PCG数据
    var pcgData by remember { mutableStateOf(generateRealisticPcgData(500)) }
    // 当前时间戳（用于动画）
    var timestamp by remember { mutableStateOf(0f) }
    // 健康指标
    var heartRate by remember { mutableStateOf(72) }
    var respirationRate by remember { mutableStateOf(16) }
    var hrv by remember { mutableStateOf(42) }
    var bpSystolic by remember { mutableStateOf(120) }
    var bpDiastolic by remember { mutableStateOf(80) }
    var isMonitoring by remember { mutableStateOf(false) }

    LaunchedEffect(isMonitoring) {
        while (isMonitoring) {
            delay(40) // 每40毫秒更新一次数据（25fps）
            timestamp += 0.04f

            // 更新波形数据
            ecgData = ecgData.drop(1) + listOf(calculateEcgPoint(timestamp))
            pcgData = pcgData.drop(1) + listOf(calculatePcgPoint(timestamp))

            // 更新健康指标（模拟实时变化）
            heartRate = (72 + sin(timestamp * 2) * 5).toInt().coerceIn(60, 100)
            respirationRate = (16 + cos(timestamp * 0.8f) * 2).toInt().coerceIn(12, 20)
            hrv = (42 + sin(timestamp * 0.5f) * 10).toInt().coerceIn(20, 80)
            bpSystolic = (120 + sin(timestamp * 0.4f) * 5).toInt().coerceIn(110, 130)
            bpDiastolic = (80 + cos(timestamp * 0.4f) * 3).toInt().coerceIn(70, 90)
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("实时心电心音监测") },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(Icons.Filled.ArrowBack, contentDescription = "返回")
                    }
                }
            )
        }
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .padding(innerPadding)
                .fillMaxSize()
                .padding(16.dp)
        ) {
            // 心电图显示区域
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(220.dp)
                    .padding(bottom = 8.dp)
            ) {
                RealTimePlot(
                    data = ecgData,
                    color = Color(0xFF4CAF50), // ECG绿色
                    label = "心电图 (ECG)",
                    gridColor = Color(0xFF333333),
                    amplitude = 50f
                )
            }

            // 心音图显示区域
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(220.dp)
                    .padding(top = 8.dp)
            ) {
                RealTimePlot(
                    data = pcgData,
                    color = Color(0xFF2196F3), // PCG蓝色
                    label = "心音图 (PCG)",
                    gridColor = Color(0xFF333333),
                    amplitude = 80f
                )
            }

            Spacer(modifier = Modifier.height(8.dp))

            // 健康指标卡片
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 8.dp),
                colors = CardDefaults.cardColors(containerColor = Color(0xFF1E1E1E))
            ) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Text(
                        text = "健康指标",
                        style = MaterialTheme.typography.titleMedium,
                        color = Color.White,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )

                    // 第一行指标
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        HealthIndicator("心率", "${heartRate} BPM", Color(0xFFEF5350))
                        HealthIndicator("呼吸频率", "${respirationRate} 次/分钟", Color(0xFF29B6F6))
                        HealthIndicator("HRV", "${hrv} ms", Color(0xFF66BB6A))
                    }

                    Spacer(modifier = Modifier.height(12.dp))

                    // 第二行指标
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        HealthIndicator("收缩压", "${bpSystolic} mmHg", Color(0xFFAB47BC))
                        HealthIndicator("舒张压", "${bpDiastolic} mmHg", Color(0xFF26A69A))
                        HealthIndicator("状态", "正常", Color(0xFFFFA726))
                    }
                }
            }

            Spacer(modifier = Modifier.height(16.dp))

            // 控制按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                Button(
                    onClick = { isMonitoring = true },
                    colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF4CAF50))
                ) {
                    Text("开始监测")
                }
                Button(
                    onClick = { isMonitoring = false },
                    colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFF44336))
                ) {
                    Text("暂停")
                }
                Button(
                    onClick = { /* 保存数据 */ },
                    colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF2196F3))
                ) {
                    Text("保存数据")
                }
            }
        }
    }
}

@Composable
fun RealTimePlot(
    data: List<Float>,
    color: Color,
    label: String,
    gridColor: Color,
    amplitude: Float
) {
    Box(modifier = Modifier.fillMaxSize()) {
        // 标签
        Text(
            text = label,
            color = color,
            style = MaterialTheme.typography.titleSmall,
            modifier = Modifier.padding(8.dp)
        )

        Canvas(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.Black)
        ) {
            val width = size.width
            val height = size.height
            val centerY = height / 2

            // 绘制网格
            val gridEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 5f), 0f)

            // 水平线
            for (i in 1..4) {
                val y = i * (height / 5)
                drawLine(
                    color = gridColor,
                    start = Offset(0f, y),
                    end = Offset(width, y),
                    strokeWidth = 1f,
                    pathEffect = gridEffect
                )
            }

            // 垂直线
            for (i in 1..9) {
                val x = i * (width / 10)
                drawLine(
                    color = gridColor,
                    start = Offset(x, 0f),
                    end = Offset(x, height),
                    strokeWidth = 1f,
                    pathEffect = gridEffect
                )
            }

            // 中心线
            drawLine(
                color = Color(0xFF555555),
                start = Offset(0f, centerY),
                end = Offset(width, centerY),
                strokeWidth = 1f,
                pathEffect = PathEffect.dashPathEffect(floatArrayOf(5f, 5f), 0f)
            )

            // 绘制波形
            if (data.size > 1) {
                val path = androidx.compose.ui.graphics.Path().apply {
                    moveTo(0f, centerY - data[0] * amplitude)

                    for (i in 1 until data.size) {
                        val x = i * (width / data.size)
                        val y = centerY - data[i] * amplitude
                        lineTo(x, y)
                    }
                }

                drawPath(
                    path = path,
                    color = color,
                    style = Stroke(width = 2f)
                )
            }
        }
    }
}

@Composable
fun HealthIndicator(label: String, value: String, color: Color) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier.width(100.dp)
    ) {
        Text(
            text = label,
            style = MaterialTheme.typography.bodySmall,
            color = Color.LightGray
        )
        Spacer(modifier = Modifier.height(4.dp))
        Text(
            text = value,
            style = MaterialTheme.typography.titleMedium,
            color = color
        )
    }
}

// 生成逼真的心电图数据
private fun generateRealisticEcgData(size: Int): List<Float> {
    return List(size) { 0f }
}

// 生成逼真的心音图数据
private fun generateRealisticPcgData(size: Int): List<Float> {
    return List(size) { 0f }
}

// 计算逼真的ECG数据点
private fun calculateEcgPoint(t: Float): Float {
    val heartRate = 72 // 每分钟心跳次数
    val heartPeriod = 60.0f / heartRate // 心跳周期（秒）
    val tMod = t % heartPeriod

    // ECG波形特征点（基于真实ECG形态）
    return when {
        // P波
        tMod < 0.1f * heartPeriod -> 0.3f * sin(20 * PI.toFloat() * tMod).toFloat()
        // PR段
        tMod < 0.15f * heartPeriod -> 0f
        // Q波
        tMod < 0.17f * heartPeriod -> -0.2f * sin(40 * PI.toFloat() * (tMod - 0.15f * heartPeriod)).toFloat()
        // R波
        tMod < 0.20f * heartPeriod -> 1.0f * sin(40 * PI.toFloat() * (tMod - 0.17f * heartPeriod)).toFloat()
        // S波
        tMod < 0.22f * heartPeriod -> -0.3f * sin(40 * PI.toFloat() * (tMod - 0.20f * heartPeriod)).toFloat()
        // ST段
        tMod < 0.30f * heartPeriod -> 0.05f
        // T波
        tMod < 0.40f * heartPeriod -> 0.4f * sin(10 * PI.toFloat() * (tMod - 0.30f * heartPeriod)).toFloat()
        // 基线
        else -> 0f
    } + 0.05f * sin(2 * PI.toFloat() * t) // 添加呼吸引起的轻微波动
}

// 计算逼真的PCG数据点
private fun calculatePcgPoint(t: Float): Float {
    val heartRate = 72 // 每分钟心跳次数
    val heartPeriod = 60.0f / heartRate // 心跳周期（秒）
    val tMod = t % heartPeriod

    // PCG波形特征（S1和S2心音）
    return when {
        // S1心音（收缩期开始）
        tMod < 0.1f * heartPeriod -> {
            0.8f * exp(-30f * (tMod - 0.02f * heartPeriod) * (tMod - 0.02f * heartPeriod)).toFloat() *
                    sin(100 * PI.toFloat() * tMod).toFloat()
        }
        // 收缩期杂音
        tMod < 0.25f * heartPeriod -> {
            0.2f * sin(30 * PI.toFloat() * tMod).toFloat() *
                    exp(-5f * (tMod - 0.1f * heartPeriod)).toFloat()
        }
        // S2心音（舒张期开始）
        tMod < 0.35f * heartPeriod -> {
            0.7f * exp(-40f * (tMod - 0.27f * heartPeriod) * (tMod - 0.27f * heartPeriod)).toFloat() *
                    sin(80 * PI.toFloat() * (tMod - 0.25f * heartPeriod)).toFloat()
        }
        // 舒张期杂音
        tMod < 0.45f * heartPeriod -> {
            0.15f * sin(25 * PI.toFloat() * (tMod - 0.35f * heartPeriod)).toFloat() *
                    exp(-4f * (tMod - 0.35f * heartPeriod)).toFloat()
        }
        // 基线
        else -> 0f
    } + 0.03f * Random.nextFloat() // 添加轻微随机噪声
}

@Preview(showBackground = true)
@Composable
fun RealTimePlotPreview() {
    CardiacmonitorTheme {
        RealTimePlotScreen(rememberNavController())
    }
}